<template>
    <PopUps :bgIndex="1000" :boxIndex="1001" widthMy='60%'  height-my="78%">
        <div class="popups-box">
            <div class="header">
                <div class="header-top">
                    <h3>{{ props.popTitle }}</h3>
                    <i class="iconfont icon-icon-cross-empty" @click="closePopUps"></i>
                </div>
                <div class="headerMain">
                    <el-form ref="formRef" :inline="true" :model="popUpsForm" :rules="rules" class="demo-form-inline">
                        <el-form-item :prop="item.name" :label="item.label" v-for="(item, index) in popUpsFormLabel"
                            :key="index" :style="{ 'min-width': `${item.minWidth}'!important'` }">
                            <!-- 输入框 -->
                            <el-input v-model="popUpsForm[item.name]" clearable v-if="!item.type || item.type == 'input'"
                                :disabled="item.disabled || props.disabled" />
                            <!-- 下拉选框 -->
                            <el-select v-model="popUpsForm[item.name]" clearable v-if="item.type == 'select'"
                                :disabled="props.disabled">
                                <el-option :label="item1.label" :value="item1.value" v-for="(item1, index) in item.client"
                                    :key="index" />
                            </el-select>
                            <!-- 日期选框 -->
                            <el-date-picker v-else-if="item.type == 'picker'" v-model="popUpsForm[item.name]" type="date"
                                :disabled="props.disabled" placeholder="请输入日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div class="main">
                <div class="main-top">
                    <h3>入库明细</h3>
                </div>
                <div class="mainContent">
                    <addTable :boder="true" :dataTable="dataTable" @createTable="createTable" @deleteRow="deleteRow"
                        :disabled="props.disabled" :typeNumber="typeNumber" :tableTitle="'入库详细编号'" />
                    <el-form :inline="true" :model="stockroomForm" class="demo-form-inline">
                        <el-form-item :label="item.label" v-for="(item, index) in stockroomFormLabel"
                            :class="item.itemClassName" :key="index"
                            :style="{ 'min-width': `${item.minWidth}'!important'` }">
                            <!-- 输入框 -->
                            <el-input v-model="stockroomForm[0][item.name]" clearable :disabled="props.disabled"
                                v-if="!item.type || item.type == 'input'" />
                            <!-- 下拉选框 -->
                            <el-select v-model="stockroomForm[0][item.name]" clearable v-else-if="item.type == 'select'"
                                :disabled="props.disabled">
                                <el-option :label="item1.label" :value="item1.value" v-for="(item1, index) in item.client"
                                    :key="index" />
                            </el-select>
                            <!-- 文本域 -->
                            <el-input v-model="stockroomForm[0][item.name]" type="textarea" :disabled="props.disabled"
                                v-else-if="item.type == 'textarea'" />
                        </el-form-item>

                    </el-form>
                    <div class="btn">
                        <el-button type="primary" @click="onSubmit(formRef)" class="submit" v-if="props.defindFlag">{{
                            props.popTitle.slice(0, 2) }}</el-button>
                        <el-button type="primary" @click="closePopUps" class="reset">取消</el-button>
                    </div>
                </div>
            </div>
        </div>
    </PopUps>
</template>
<script setup>
import PopUps from '@/components/My/PopUps';
import addTable from './components/addTable';
import { reactive, ref, defineEmits, watch, defineProps, onMounted } from 'vue'
import { createInsertStockroomApi,querySelectSupplierApi } from '@/api/inventory';
import { ElMessage, ElMessageBox } from 'element-plus'
const emit = defineEmits(['popUpsFlase'])
const formRef = ref(null)
let props = defineProps(['popTitle', 'disabled', 'defindFlag', 'PopData'])
let typeNumber = ref(false)
// 表单
let popUpsForm = ref({
    stockroomId: '后台生成',      // 入库编号
    supplierName: '',      // 供应商名称
    stockroomType: '',    // 入库类型
    stockroomDate: '',      // 入库日期
    purchaser: '',       // 采购人
    stockroomWarehouse: '',       // 入库仓库
    // estimatedDeliveryDate: '',       // 预计交付日期
})
// 表单数据标题
let popUpsFormLabel = ref([
    {
        name: 'stockroomId',
        label: '入库编号',
        disabled: true
    },
    {
        name: 'supplierName',
        label: '供应商名称',
        type: 'select',
        client: [
          
        ]
    },
    {
        name: 'stockroomType',
        label: '入库类型',
    
    },
    {
        name: 'stockroomDate',
        label: '入库日期',
        type: 'picker',
        minWidth: '120px'
    },
    {
        name: 'purchaser',
        label: '采购人',
    },
    {
        name: 'stockroomWarehouse',
        label: '入库仓库',
    },
    // {
    //     name: 'estimatedDeliveryDate',
    //     label: '预计交付日期',
    //     type: 'picker'
    // }
])
// 新增表格数据
let dataTable = ref([
    {
        stockroomDetailsId: '',   // 入库详细编号
        productName: '',    // 存货名称
        specs: '',          // 规格型号
        unit: '',           // 单位
        price: '',      // 成本单价
        stockroomNumber: '',        // 入库数量
        amount: '',          // 金额
    }
])
// 入库明细表单
let stockroomForm = ref([
    {
        totalPrice: '',      // 总金额
        preferential: '',    // 优惠
        discountedAmount: '',      // 折后金额
        freight: '',       // 运费
        prepayments: '',       // 预付款
        paymentAccount: '',       // 付款账户
        remarks: '',       // 备注
    }
])
// 入库明表单数据标题
let stockroomFormLabel = ref([
    {
        name: 'totalPrice',
        label: '总金额',
    },
    {
        name: 'preferential',
        label: '优惠',
    },
    {
        name: 'discountedAmount',
        label: '折后金额',
    },
    {
        name: 'freight',
        label: '运费',
    },
    {
        name: 'prepayments',
        label: '预付款',
    },
    {
        name: 'paymentAccount',
        label: '付款账户',
    },
    {
        name: 'remarks',
        label: '备注',
        type: 'textarea',
        itemClassName: 'remarks',
    },
])
// 入库信息校验
const rules = reactive({
    supplierName: [
        {
            required: true,
            message: '供应商名称',
            trigger: 'change',
        }
    ],
    stockroomType: [
        {
            required: true,
            message: '入库类型',
            trigger: 'change',
        },
    ],
    stockroomDate: [
        {
            required: true,
            message: '入库日期',
            trigger: 'change',
        },
    ],
    purchaser: [
        {
            required: true,
            message: '采购人',
            trigger: 'change',
        },
    ],
    stockroomWarehouse: [
        {
            required: true,
            message: '入库仓库',
            trigger: 'change',
        },
    ],
    estimatedDeliveryDate: [
        {
            required: true,
            message: '预计交付日期',
            trigger: 'change',
        },
    ],
})
// 创建表格一行表格
const createTable = () => {
    if (props.disabled) return
    dataTable.value.push({
        stockroomDetailsId: '',   // 入库详细编号
        productName: '',    // 存货名称
        specs: '',          // 规格型号
        unit: '',           // 单位
        price: '',      // 成本单价 
        stockroomNumber: '',        // 入库数量
        amount: '',          // 金额
        delete: true
    })
}
// 删除表格一行表格
const deleteRow = (v) => {
    dataTable.value.splice(v.$index, 1)
}
// 提交
const onSubmit = (formRef) => {
    ElMessageBox.confirm(
        '确认' + props.popTitle + '吗?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'success',
        }
    ).then(async () => {
        if (!formRef) return
        await formRef.validate((valid, fields) => {
            if (valid) {
                if (props.popTitle.slice(0, 2) == '新增') {
                    // 发送新增接口请求
                    popUpsForm.value.stockroomId = ''
                    let parasm = Object.assign(popUpsForm.value, stockroomForm.value[0])
                    parasm.stockroomDetailVOS = dataTable.value
                    popUpsForm.value.supplierId = popUpsForm.value.supplierName
                    createInsertStockroomApi(parasm).then(res => {
                        popUpsForm.value.stockroomId = '后台生成'
                        if (res.code == 200) {
                            emit('getoutboundOrderData')
                            closePopUps()
                            ElMessage({
                                type: 'success',
                                message: res.msg,
                            })
                        }
                    })
                } else if (props.popTitle.slice(0, 2) == '修改') {
                    let parasm = Object.assign(popUpsForm.value, stockroomForm.value[0])
                    parasm.stockroomDetailVOS = dataTable.value
                    createInsertStockroomApi(parasm).then(res => {
                        popUpsForm.value.stockroomId = '后台生成'
                        if (res.code == 200) {
                            emit('getoutboundOrderData')
                            closePopUps()
                            ElMessage({
                                type: 'success',
                                message: res.msg,
                            })
                        }
                    })
                }

            } else {
                // console.log('error submit!', fields)
                console.log(popUpsForm.value);
            }
        })
    })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '已取消',
            })
        })

}
// 关闭
const closePopUps = () => {
    emit('popUpsFlase', false)
}
// 计算材料安装城管费
watch(dataTable.value, (val) => {
    // 总金额
    let totalMoney = 0
    val.forEach(v => {
        totalMoney += Number(v.amount)
        // 计算每个工单表格 金额
        v.amount = v.stockroomNumber * v.price ? v.stockroomNumber * v.price : 0
    })
    // 总金额
    stockroomForm.value[0].totalPrice = totalMoney
}, {
    immediate: true,
    deep: true
})
// 数据回显
const assignmentFun = () => {
    // 表单
    let {
        stockroomId,      // 入库编号
        supplierName,      // 供应商名称
        stockroomType,    // 入库类型
        stockroomDate,      // 入库日期
        purchaser,       // 采购人
        stockroomWarehouse,       // 入库仓库
        // estimatedDeliveryDate,       // 预计交付日期
    } = props.PopData
    popUpsForm.value = {
        stockroomId,      // 入库编号
        supplierName,      // 供应商名称
        stockroomType,    // 入库类型
        stockroomDate,      // 入库日期
        purchaser,       // 采购人
        stockroomWarehouse,       // 入库仓库
        // estimatedDeliveryDate,       // 预计交付日期
    }
   

    // 表格
    dataTable.value = props.PopData.stockroomDetailVOS

    // 尾部表单
    let {
        totalPrice,      // 总金额
        preferential,    // 优惠
        discountedAmount,      // 折后金额
        freight,       // 运费
        prepayments,       // 预付款
        paymentAccount,       // 付款账户
        remarks,       // 备注
    } = props.PopData
    stockroomForm.value[0] = {
        totalPrice,      // 总金额
        preferential,    // 优惠
        discountedAmount,      // 折后金额
        freight,       // 运费
        prepayments,       // 预付款
        paymentAccount,       // 付款账户
        remarks,       // 备注
    }
}

const querySelectSupplierApiFn = async()=>{
   let {code,rows} = await querySelectSupplierApi()
    if(code == 200){
        rows.forEach(v=>{
            popUpsFormLabel.value[1].client.push({
                label:v.supplierName,
                value:v.supplierId
            }) 
        })
    }
}
onMounted(() => {
    querySelectSupplierApiFn()
    // 数据回显
    if (!props.defindFlag) {
        assignmentFun()
    }
})
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

.el-input__wrapper {
    --el-select-width: 220px;
}

:deep(.el-form-item) {
    width: 250px;
}

:deep(.el-form-item__label) {
    width: 150px;
    text-align: right;
}

@mixin publicH3 {
    font-weight: 550;
    position: relative;
    font-size: 16px !important;

    &::after {
        content: '';
        width: 5px;
        height: 20px;
        background-color: #1947FF;
        border-radius: 5px;
        position: absolute;
        left: -15px;
        top: 0px;
    }
}

@mixin titlePadding {
    padding: 25px 25px 25px 45px;
}

@mixin pubilcForm {
    :deep(.el-form-item) {
        margin-right: 30px !important;
    }

    :deep(.el-form-item__label) {
        font-size: 14px;
    }

    :deep(.el-input__wrapper) {
        width: 132px;
    }

    :deep(.el-date-editor--datetimerange) {
        width: 240px;
    }

    :deep(.el-table .el-table__header-wrapper th, .el-table .el-table__fixed-header-wrapper th) {
        font-size: 15px !important;
    }
}

.popups-box {
    max-height: 650px;
    overflow-y: scroll;

    .header {
        .header-top {
            @include titlePadding;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0px;
            background: #FFF;
            z-index: 2024;

            h3 {
                @include publicH3;
            }

            .iconfont {
                color: #666;
                font-size: 27px;
            }
        }

        .headerMain {
            .demo-form-inline {
                @include pubilcForm;
            }
        }
    }

    .main {
        .main-top {
            @include titlePadding;

            h3 {
                @include publicH3;
            }
        }

        .mainContent {
            padding: 20px;

            .remarks {
                width: 400px;
            }

            .demo-form-inline {
                margin-top: 20px;
                @include pubilcForm;

            }

            .btn {
                text-align: right;

                .el-button {
                    width: 50px;
                    height: 25px;
                    font-size: 12px;
                }

                .reset {
                    background-color: #E4E9FC;
                    color: #333;
                    border: none;
                }
            }
        }
    }
}</style>